package com.sgcc.epri.dcloud.conf.db;

import org.apache.ibatis.executor.resultset.ResultSetHandler;
import org.apache.ibatis.plugin.*;

import java.sql.Statement;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;

@Intercepts({
        @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class})
})
public class LowerCaseInterceptor implements Interceptor {
    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        Object result = invocation.proceed();
        if (result instanceof Collection) {
            for (Object item : (Collection) result) {
                if (item instanceof Map) {
                    processMap((Map) item);
                }
            }
        }
        return result;
    }

    private void processMap(Map<String, Object> map) {
        Map<String, Object> temp = new LinkedHashMap<>();
        map.forEach((k, v) -> temp.put(k.toLowerCase(), v));
        map.clear();
        map.putAll(temp);
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {}
}